import React, { Component } from 'react'
import { connect } from 'dva';
import XLSX from "xlsx";
import { Row, Button, Skeleton, Table, message, Modal } from 'antd';
import { exportExcl } from '@/utils/xlsx';
import SearchAnalyse from './components/SearchAnalyse';
import {queryRiskCount} from './service';
import styled from './styled.less';
import {TOTAL} from './enum';
import { checkInit, isNumber } from '@/utils/util';

interface IProps {
  dispatch?: Function,
  children?: React.ReactNode,
  total?: object,
  questionData?: {
    data: Array<any>,
    dataCnt: number
  }
}

@connect(({ analyse_danger }) => ({
  total: analyse_danger.total || {},
  questionData: analyse_danger.questionData
}))
class DeviceFireHost extends Component<IProps> {

  state = {
    current: 1,
    allData: {
      riskNum: '',
      rectifiedNum: '',
      unRectifiedNum: '',
      rectifiedRate: ''
    },
    visible: false,
    imageList: []
  };

  queryData = (params) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'analyse_danger/queryQuestion',
      payload: params
    });
  };

  initCurrent = () => {
    this.setState({
      current: 1
    })
  };

  handleExport = e => {
    const { questionData = {data: []} }  = this.props;
    const { data } = questionData;
    const ans = data && Array.isArray(data) && data.map(item => {
      return {
        '隐患': item.name ? item.name : item.fireRoomName,
        '图片': Array.isArray(item.attachList) ? item.attachList.join(',') : '',
        '上报时间': item.updateTime,
        '上报人': item.updaterName,
        '位置': item.targetLocation,
        '设备ID': item.networkAddr,
        '设备名称': item.deviceName,
        '检查项目': item.reportName,
        '整改人': item.rectifierName,
        '整改时间': item.rectifiedTime,
        '整改照片': Array.isArray(item.rectifieAttachList) ? item.rectifieAttachList.join(',') : '',
        '整改描述': item.rectifieDesc
      }
    });

    exportExcl({
      XLSX,
      data: ans,
      name: "隐患统计",
      fileName: "隐患统计"
    })
  };

  showModal = (value) => {
    this.setState({
      visible: true,
      imageList: value
    });
  };

  handleOk = (e) => {
    this.setState({
      visible: false,
    });
  };

  handleCancel = (e) => {
    this.setState({
      visible: false,
    });
  };

  componentDidMount() {
    message.loading('', 0.6);
    checkInit();
    queryRiskCount().then(data => {
      if(data) {
        this.setState({
          allData: {
            riskNum: data.riskNum,
            rectifiedNum: data.rectifiedNum,
            unRectifiedNum: data.unRectifiedNum,
            rectifiedRate: data.rectifiedRate
          }
        })
      }
    });
    this.queryData({
      pageNum: 1,
      pageSize: 10
    });
  }

  toPercentage(value = 0) {
    return `${isNumber(+value) ? (+value * 100).toFixed(2) : 0} %`;
  }

  render() {
    const { questionData = {data: [], dataCnt: 0} }  = this.props;
    const { data, dataCnt } = questionData;
    const ans = data && Array.isArray(data) ? data.map((item, index) => ({
        key: index,
      name: item.fireRoomName ? item.fireRoomName : item.name,
      attachList: item.attachList ? item.attachList : ' ',
      updateTime: item.updateTime ? item.updateTime : ' ',
      updaterName: item.updaterName ? item.updaterName : ' ',
      targetLocation: item.targetLocation ? item.targetLocation : ' ',
      networkAddr: item.networkAddr ? item.networkAddr : ' ',
      deviceName: item.deviceName ? item.deviceName : ' ',
      reportName: item.reportName ? item.reportName : ' ',
      rectifierName: item.rectifierName ? item.rectifierName : ' ',
      rectifiedTime: item.rectifiedTime ? item.rectifiedTime : ' ',
      rectifieAttachList: item.rectifieAttachList ? item.rectifieAttachList : ' ',
      rectifieDesc: item.rectifieDesc ? item.rectifieDesc : ' ',
      })
    ) : [];

    const pagination = {
      total: dataCnt,
      showTotal: total => `共 ${total} 条`,
      showQuickJumper: true,
      pageSize: 10,
      onChange: (current) => {
        this.setState({
          current,
          isChangePage: true
        });
        this.queryData({
          pageSize: 10,
          pageNum: current
        })
      },
    };

    const columns = [{
      title: '隐患',
      dataIndex: 'name',
    }, {
      title: '图片',
      dataIndex: 'attachList',
      render: (value) => {
        if(Array.isArray(value)) {
          return (<span style={{'color': '#40a9ff', 'cursor': 'pointer'}} onClick={() => { this.showModal(value) }}>{value.length}</span>);
        } else {
          return (<span>/</span>)
        }
      }
    }, {
      title: '上报时间',
      dataIndex: 'updateTime',
    }, {
      title: '上报人',
      dataIndex: 'updaterName'
    }, {
      title: '位置',
      dataIndex: 'targetLocation'
    }, {
      title: '设备ID',
      dataIndex: 'networkAddr'
    }, {
      title: '设备名称',
      dataIndex: 'deviceName'
    }, {
      title: '检查项目',
      dataIndex: 'reportName'
    }, {
      title: '整改人',
      dataIndex: 'rectifierName'
    }, {
      title: '整改照片',
      dataIndex: 'rectifieAttachList',
      render: (value) => {
        if(Array.isArray(value)) {
          return (<span style={{'color': '#40a9ff', 'cursor': 'pointer'}} onClick={() => {this.showModal(value)}}>{value.length}</span>);
        } else {
          return (<span>/</span>)
        }
      }
    }, {
      title: '整改描述',
      dataIndex: 'rectifieDesc'
    }, {
      title: '整改时间',
      dataIndex: 'rectifiedTime'
    }];

    return (
      <>
        <div className={styled.device_statistical}>
          {
            Array.isArray(TOTAL) ? TOTAL.map((item, index) => (
              <span key={index}><img src={item.icon} style={{'marginRight': '10px'}}/>{item.name}：{item.func ? this[item.func](this.state.allData[item.key]): this.state.allData[item.key] }</span>
            )) : null
          }
        </div>
        <SearchAnalyse
          current={ this.state.current }
          initCurrent={this.initCurrent}
          handleExport={this.handleExport}
        />
        <Table
          columns={columns}
          pagination={pagination}
          dataSource={ans}
          bordered
        />
        <Modal
          title="照片列表"
          visible={this.state.visible}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
        >
          <div style={{'display': 'flex', 'flexWrap': 'wrap'}}>
            {
              this.state.imageList.map((item, index) => (
                <div key={index} style={{'width': '30%', 'margin': '1%'}}><img src={item} style={{'width': '100%'}}/></div>
              ))
            }
          </div>
        </Modal>
      </>
    );
  }
}

export default DeviceFireHost;
